<template>
  <div class="rider-layout">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content">
        <div class="logo-section">
          <img src="/logo.png" alt="饱了么" class="logo" />
          <span class="title">骑手工作台</span>
        </div>
        
        <div class="center-section">
          <span class="online-time" v-if="isOnline">
            在线时长: {{ onlineTime }}
          </span>
        </div>

        <div class="right-section">
          <div class="status-section">
            <el-switch
              v-model="isOnline"
              :active-text="isOnline ? '在线' : '离线'"
              @change="toggleOnlineStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              class="status-switch"
            />
          </div>
          
          <div class="user-section">
            <el-dropdown @command="handleUserAction">
              <el-button type="text" class="user-btn">
                <el-icon><User /></el-icon>
                {{ userInfo.realName || '骑手中心' }}
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="content-wrapper">
        <slot />
      </div>
    </main>

    <!-- 底部状态栏 -->
    <footer class="footer">
      <div class="footer-content">
        <div class="stats-summary">
          <span class="stat-item">
            今日订单: <strong>{{ todayStats.orders }}</strong>
          </span>
          <span class="stat-item">
            今日收益: <strong>¥{{ todayStats.earnings }}</strong>
          </span>
          <span class="stat-item">
            评分: <strong>{{ userInfo.rating || '暂无' }}</strong>
          </span>
        </div>
        <div class="location-info">
          <el-icon><Location /></el-icon>
          <span>{{ currentLocation || '位置获取中...' }}</span>
        </div>
      </div>
    </footer>

    <!-- 催单通知弹窗 -->
    <UrgentOrderNotification
      v-model:visible="showUrgentNotification"
      :title="urgentNotification.title"
      :message="urgentNotification.message"
      :duration="10000"
      :enable-vibration="true"
      @close="handleUrgentNotificationClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  User, 
  ArrowDown, 
  SwitchButton,
  Location
} from '@element-plus/icons-vue';
import { riderApi } from '@/api/rider';
import { getToken, getRiderId } from '@/utils/auth';
import { wsService, MESSAGE_TYPES } from '@/utils/websocket';
import UrgentOrderNotification from './UrgentOrderNotification.vue';
import type { WorkStatus } from '@/types/rider';

const router = useRouter();

// 用户信息
const userInfo = reactive({
  realName: '',
  rating: 0,
  phone: '',
  vehicleType: '',
  vehicleNumber: ''
});

// 在线状态
const isOnline = ref(false);
const onlineTime = ref('0小时0分钟');
const currentLocation = ref('');

// 获取骑手当前状态
const getRiderCurrentStatus = async () => {
  try {
    const response = await riderApi.getCurrentStatus();
    if (response.data && response.data.data) {
      const status = response.data.data;
      isOnline.value = status === 'ONLINE';
      
      if (isOnline.value) {
        onlineStartTime = new Date();
        startOnlineTimer();
      }
    }
  } catch (error) {
    console.error('获取骑手状态失败:', error);
    isOnline.value = false;
  }
};

// 今日统计
const todayStats = reactive({
  orders: 0,
  earnings: 0
});

// 催单通知相关
const showUrgentNotification = ref(false);
const urgentNotification = reactive({
  title: '催单提醒',
  message: '您有新的催单消息，请及时处理订单！'
});

// WebSocket连接状态
const wsConnected = ref(false);

// 在线时长计时器
let onlineTimer: number | null = null;
let onlineStartTime: Date | null = null;

// 切换在线状态
const toggleOnlineStatus = async () => {
  try {
    const status: WorkStatus = isOnline.value ? 'ONLINE' : 'OFFLINE';
    await riderApi.updateWorkStatus(status);
    
    if (isOnline.value) {
      onlineStartTime = new Date();
      startOnlineTimer();
      // 上线时连接WebSocket
      connectWebSocket();
      ElMessage.success('已上线，开始接单');
    } else {
      stopOnlineTimer();
      // 下线时断开WebSocket
      disconnectWebSocket();
      ElMessage.info('已下线，停止接单');
    }
  } catch (error) {
    console.error('更新工作状态失败:', error);
    // 回滚状态
    isOnline.value = !isOnline.value;
    ElMessage.error('状态更新失败，请重试');
  }
};

// 连接WebSocket
const connectWebSocket = async () => {
  const token = getToken();
  if (!token) {
    console.error('无法获取token，无法连接WebSocket');
    return;
  }

  try {
    console.log('骑手上线，开始连接WebSocket...');
    
    // 连接WebSocket
    await wsService.connect(token);
    
    // 监听连接状态
    wsService.on(MESSAGE_TYPES.CONNECTION_STATUS, (data: any) => {
      wsConnected.value = data.connected;
      console.log('WebSocket连接状态:', data.connected ? '已连接' : '已断开');
    });
    
    // 监听催单消息
    wsService.on(MESSAGE_TYPES.USER_ORDER_URGENT, handleUrgentMessage);
    
    // 设置兼容回调
    wsService.onUrgentOrderReceived = handleUrgentMessage;
    
    console.log('WebSocket连接设置完成');
  } catch (error) {
    console.error('WebSocket连接失败:', error);
  }
};

// 断开WebSocket连接
const disconnectWebSocket = () => {
  console.log('骑手下线，断开WebSocket连接');
  
  // 移除催单消息监听
  wsService.off(MESSAGE_TYPES.USER_ORDER_URGENT, handleUrgentMessage);
  wsService.off(MESSAGE_TYPES.CONNECTION_STATUS, () => {});
  
  // 清除兼容回调
  wsService.onUrgentOrderReceived = undefined;
  
  // 断开连接
  wsService.close();
  wsConnected.value = false;
};

// 处理催单消息
const handleUrgentMessage = (data: any) => {
  console.log('收到催单消息:', data);
  
  // 检查是否针对当前骑手
  const currentRiderId = getRiderId();
  const targetRiderId = data.riderId || data.rider_id || data.targetRiderId;
  
  if (targetRiderId && currentRiderId && targetRiderId.toString() !== currentRiderId.toString()) {
    console.log('催单消息不是针对当前骑手');
    return;
  }
  
  // 更新催单通知内容
  urgentNotification.title = data.title || '催单提醒';
  urgentNotification.message = data.message || data.content || '您有新的催单消息，请及时处理订单！';
  
  // 显示催单通知
  showUrgentNotification.value = true;
  
  console.log('显示催单通知弹窗');
};

// 关闭催单通知
const handleUrgentNotificationClose = () => {
  showUrgentNotification.value = false;
  console.log('催单通知弹窗已关闭');
};

// 开始在线计时
const startOnlineTimer = () => {
  onlineTimer = window.setInterval(() => {
    if (onlineStartTime) {
      const now = new Date();
      const diff = now.getTime() - onlineStartTime.getTime();
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      onlineTime.value = `${hours}小时${minutes}分钟`;
    }
  }, 60000); // 每分钟更新一次
};

// 停止在线计时
const stopOnlineTimer = () => {
  if (onlineTimer) {
    clearInterval(onlineTimer);
    onlineTimer = null;
  }
  onlineStartTime = null;
  onlineTime.value = '0小时0分钟';
};

// 获取位置信息
const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        // 这里可以调用地理编码API获取具体地址
        currentLocation.value = `${latitude.toFixed(4)}, ${longitude.toFixed(4)}`;
        
        // 更新服务器位置
        riderApi.updateLocation({
          latitude,
          longitude,
          timestamp: new Date().toISOString()
        }).catch(console.error);
      },
      (error) => {
        console.error('获取位置失败:', error);
        currentLocation.value = '位置获取失败';
      }
    );
  } else {
    currentLocation.value = '不支持定位';
  }
};

// 获取今日统计
const getTodayStats = async () => {
  try {
    const response = await riderApi.getStats('day');
    if (response.data) {
      // 根据API返回的实际字段名映射数据
      todayStats.orders = response.data.ordersCount || 0;
      todayStats.earnings = response.data.totalIncome || 0;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 用户操作处理
const handleUserAction = (command: string) => {
  switch (command) {
    case 'logout':
      handleLogout();
      break;
  }
};

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    // 如果在线状态，先下线并断开WebSocket
    if (isOnline.value) {
      isOnline.value = false;
      await riderApi.updateWorkStatus('OFFLINE');
      disconnectWebSocket();
    }
    
    // 清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('userRole');
    
    ElMessage.success('已退出登录');
    router.push('/rider/login');
  } catch {
    // 用户取消退出
  }
};

// 初始化数据
const initializeData = async () => {
  try {
    // 获取用户信息（这里模拟，实际应该从API获取）
    userInfo.realName = '张师傅';
    userInfo.rating = 4.8;
    userInfo.phone = '138****8888';
    userInfo.vehicleType = 'ELECTRIC';
    userInfo.vehicleNumber = '京A12345';
    
    // 获取骑手当前状态
    await getRiderCurrentStatus();
    
    // 获取今日统计
    await getTodayStats();
    
    // 获取当前位置
    getCurrentLocation();
    
    // 位置更新定时器（每5分钟更新一次）
    setInterval(getCurrentLocation, 5 * 60 * 1000);
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
};

onMounted(() => {
  initializeData();
});

onUnmounted(() => {
  stopOnlineTimer();
  // 组件卸载时断开WebSocket连接
  if (wsConnected.value) {
    disconnectWebSocket();
  }
});
</script>

<style scoped>
.rider-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f7fa;
}

/* 头部导航 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  max-width: 1400px;
  margin: 0 auto;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 0 0 auto;
}

.logo {
  width: 36px;
  height: 36px;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.center-section {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 20px;
  flex: 0 0 auto;
}

.status-section {
  display: flex;
  align-items: center;
}

.status-switch {
  --el-switch-on-color: #13ce66;
  --el-switch-off-color: #ff4949;
}

.online-time {
  font-size: 14px;
  color: #e8f4fd;
  white-space: nowrap;
}

.user-section {
  display: flex;
  align-items: center;
}

.user-btn {
  color: white !important;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1) !important;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s;
  font-size: 14px;
}

.user-btn:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.user-btn .el-icon {
  color: white;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f5f7fa;
}

/* 底部状态栏 */
.footer {
  background: white;
  border-top: 1px solid #e4e7ed;
  padding: 10px 20px;
  flex-shrink: 0;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
  font-size: 14px;
}

.stats-summary {
  display: flex;
  gap: 24px;
}

.stat-item {
  color: #606266;
}

.stat-item strong {
  color: #409eff;
  font-weight: 600;
}

.location-info {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .header-content {
    flex-wrap: nowrap;
    height: 60px;
    padding: 0 10px;
  }
  
  .logo-section .title {
    display: none;
  }
  
  .center-section {
    flex: 0 0 auto;
    margin: 0 10px;
  }
  
  .right-section {
    gap: 10px;
  }
  
  .footer-content {
    flex-direction: column;
    gap: 8px;
  }
  
  .stats-summary {
    justify-content: center;
    flex-wrap: wrap;
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .content-wrapper {
    padding: 10px;
  }
  
  .header-content {
    padding: 0 5px;
  }
  
  .right-section {
    gap: 8px;
  }
  
  .online-time {
    font-size: 12px;
  }
  
  .user-btn {
    font-size: 12px;
    padding: 6px 12px;
  }
  
  .user-btn span {
    display: none;
  }
}
</style>
